package cn.acewill.yxd.yunxundian.ui.schedule;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.AddSchdeuleOEAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.model.SchAddBean;
import cn.acewill.yxd.yunxundian.pubClass.SimpleSpinnerOption;
import cn.acewill.yxd.yunxundian.pubClass.multiSelect;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SignInActivity;
import cn.acewill.yxd.yunxundian.ui.sign.WrittingEvaluationListActivity;
import cn.acewill.yxd.yunxundian.ui.sign.YxdEvaluationListActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

import static cn.acewill.yxd.yunxundian.adapter.AddSchdeuleOEAdapter.BtnCallBack;

/**
 * Created by AAA on 2017/8/1.
 */

public class schAddForOE extends BaseActivity implements View.OnClickListener{
    private Toolbar mytoolbar;
    private Button addTaskType,addStore;
    private LinearLayout taskLinear;
    private ListView myTaskList;
    private YXDAPP yxdapp=new YXDAPP();
    private DbManager db = x.getDb(yxdapp.getDaoConfig());
    List<SimpleSpinnerOption> lst = new ArrayList<>();
    List<SimpleSpinnerOption> shopLst=new ArrayList<>();
    //展示数据的list
    List<SchAddBean> addlist = new ArrayList<>();
    private AddSchdeuleOEAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_schby_oe);
        initView();
    }
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_do_sch, menu);
//        return super.onCreateOptionsMenu(menu);
//    }

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()){
//            case R.id.action_Dosch:
//                if (addlist.size()==0){
//                    //showdialog
//                    showMyExitDialg(1);
//                }else{
//                    startActivity(new Intent(this, MainActivity.class)
//                            .putExtra("userId",MainActivity.id).putExtra("userName",MainActivity.firstName));
//                }
//
//        }
//        return super.onOptionsItemSelected(item);
//    }

    private void initView(){
        this.mytoolbar = (Toolbar) findViewById(R.id.myToolBar);
        mytoolbar.setTitle("");
        setSupportActionBar(mytoolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mytoolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(102);
                finish();
            }
        });
        this.addStore = (Button) findViewById(R.id.addStore);
        this.addTaskType = (Button) findViewById(R.id.addTaskType);
        taskLinear = (LinearLayout) findViewById(R.id.taskLinear);
        myTaskList = (ListView) findViewById(R.id.myTaskList);
        addStore.setOnClickListener(this);
        addTaskType.setOnClickListener(this);

        if (addlist!=null && addlist.size()>0){
            taskLinear.setVisibility(View.VISIBLE);
        }else{
            taskLinear.setVisibility(View.GONE);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v) {
        try {
            getLst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        switch (v.getId()){
            case R.id.addStore:
                if (!Objects.equals(storeStr, "")){
                    storeStr="";
                }
                if (addlist!=null && addlist.size()>0){
                    BaseActivity.showAnimaDialog(this,"请先操作当前任务");
                }else{
                    Intent sel = new Intent(this, multiSelect.class);
                    sel.putExtra("lstData", JSON.toJSONString(shopLst));
                    sel.putExtra("title", "请选择任务类型");
                    sel.putExtra("xuanze", "dan");
                    sel.putExtra("daima", "shop");
                    //startActivity(sel);
                    startActivityForResult(sel, 1);
                }
                break;
            case R.id.addTaskType:
                if (!Objects.equals(typeStr, "")){
                    typeStr="";
                }
                if (addlist!=null && addlist.size()>0){
                    BaseActivity.showAnimaDialog(this,"请先操作当前任务");
                }else{
                    Intent store=new Intent(this, multiSelect.class);
                    store.putExtra("lstData", JSON.toJSONString(lst));
                    store.putExtra("title","请选择门店");
                    store.putExtra("xuanze","dan");
                    store.putExtra("daima","sch");
                    startActivityForResult(store,1);
                }
                break;
        }
    }
    private void  getLst() throws DbException {
        Employee emps = db.selector(Employee.class).where("ID","=", MainActivity.id).findFirst();
        if (emps!=null){
            List<CommonMapBean> comList = db.selector(CommonMapBean.class).where("ServerId","=",emps.getID())
                    .and("cmType","=","role").findAll();
            int isall = 1;
            int isOE = 0;
            if (comList!=null&&comList.size()>0){

                for (CommonMapBean cc : comList){

                    if(cc.getCmValue().equals("OM"))
                        isall=0;
                    else if(cc.getCmValue().equals("OC"))
                        isall=0;
                    else if(cc.getCmValue().equals("OE")) {
                        isall = 1;
                        isOE = 1;
                    }
                    else
                        isall=1;
                }
            }
            List<sType> typeList;
            if(isOE==0)
                typeList=db.selector(sType.class).where("isToShop","=","1")
                        .and("areaId","like",emps.getDiqu()==null?"-%":("%-"+emps.getDiqu().toString()+"-%")).findAll();
            else
                typeList=db.selector(sType.class).where("isToShop","=","1")
                        .and("departmentId","like",emps.getDepartmentId()==0?"-%":("%-"+emps.getDepartmentId()+"-%")).findAll();
            if(typeList!=null)
            {
                //清空之前数据
                if (lst!=null&&lst.size()>0){
                    lst.clear();
                }
                for (sType ss:typeList) {
                    SimpleSpinnerOption ci=new SimpleSpinnerOption();
                    ci.setValue(String.valueOf(ss.getID()));
                    ci.setName(ss.getTypeName());
                    lst.add(ci);
                }
            }
            List<Shop> shopList=null;
            if(isall==0)
                shopList=db.selector(Shop.class).where("ocid","=",String.valueOf(emps.getID())).or("omid","=",String.valueOf(emps.getID())).findAll();

            if(shopList==null)
                shopList=db.selector(Shop.class).findAll();
            if(shopList!=null)
            {
                if (shopList.size() > 0){
                    shopLst.clear();
                }
                for(Shop thiS:shopList){
                    SimpleSpinnerOption shopS=new SimpleSpinnerOption();
                    shopS.setName(thiS.getShopName());
                    shopS.setValue(String.valueOf(thiS.getID()));
                    shopLst.add(shopS);
                }
            }
        }
    }
    String sYear="",sMonth="",sDay="",sHH="",sMM="";
    String storeStr = "",typeStr = "",storeid = "",typeid = "";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1){
            if(requestCode==1){
                Gson gson = new Gson();
                String result = data.getStringExtra("result");
                String rdaima=data.getStringExtra("daima");
                Type typeList = new TypeToken<ArrayList<SimpleSpinnerOption>>() {
                }.getType();
                ArrayList<SimpleSpinnerOption> results = gson.fromJson(pubClass.convertToArrayJsonNormal(result), typeList);
                if(rdaima.equals("shop")) {
                    shopLst = results;
                    if (results != null) {
                        for (SimpleSpinnerOption s : results) {
                            if (s.isChecked()){
                                storeStr += s.getName()+",";
                                storeid = String.valueOf(s.getValue());
                            }
                        }
                        if (!storeStr.equals("")) {
                            storeStr = storeStr.substring(0, storeStr.length() - 1);
                            addStore.setText(storeStr);
                        } else {
                            addStore.setText("请选择餐厅");
                        }
                    }
                }
                else
                {
                    lst=results;
                    if (results != null) {
                        for (SimpleSpinnerOption s :
                                results) {
                            if (s.isChecked()){
                                typeStr += s.getName()+",";
                                typeid = String.valueOf(s.getValue());
                            }
                        }
                        if (!typeStr.equals("")) {
                            typeStr = typeStr.substring(0, typeStr.length() - 1);
                            addTaskType.setText(typeStr);
                        } else {
                            addTaskType.setText("请选择任务类型");
                        }
                    }
                }
                //提交任务
                if (!storeStr.equals("")&&!typeStr.equals("")){
                    updateListView();
                }
            }
        }
    }

    public void updateListView(){
        YEARMMDD();
        String str=sYear+"-"+sMonth+"-"+sDay+"T"+sHH+":"+sMM;
        final SchAddBean addBean = new SchAddBean();
        addBean.setEmpid(String.valueOf(MainActivity.id));
        addBean.setSchStartTime(str);
        addBean.setSchTypeStr(typeStr);
        addBean.setShopid(storeid);
        addBean.setStypeid(typeid);
        addBean.setShopname(storeStr);
        addlist.add(addBean);
//        clearData();
        if (addlist!=null && addlist.size()>0){
            taskLinear.setVisibility(View.VISIBLE);
        }else{
            taskLinear.setVisibility(View.GONE);
        }
        adapter = new AddSchdeuleOEAdapter(this, addlist, new BtnCallBack() {
            @Override
            public void sureClick(SchAddBean bean,int position) {
                saveSchToServer(bean);
            }
            @Override
            public void cancleClick(SchAddBean bean,int positon) {
                //移出list
                addlist.remove(positon);
                adapter.notifyDataSetChanged();
                if (addlist.size()==0){
                    taskLinear.setVisibility(View.GONE);
                }
                clearData();
            }
        });
        myTaskList.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    //上传
    public void saveSchToServer(SchAddBean bean) {
        if (NetWorkStateReceiver.whetherConnectNetWork == 1) {
            //添加到addlist中
            if (bean != null) {
//                OKHttpUICallback.ResultCallback callback=new OKHttpUICallback.ResultCallback() {
//                    @Override
//                    public void onSuccess(String result) {
//                        AsynData ad=new AsynData();
//                        ad.asynScheduleData(result.toString());
//                        if(pubClass.dialog!=null)
//                            pubClass.dialog.dismiss();
//                    }
//                    @Override
//                    public void onError(Call call, IOException e) {
//                        if(pubClass.dialog!=null) {
//                            pubClass.dialog.setTitle("提交失败，请检查网络状况");
//                        }
//                    }
//                };
//                Map<String,String> map=new HashMap<>();
//                map.put("task","addSchToServerWithType");
//                map.put("schjson",JSON.toJSONString(bean));
//                pubClass.dialog = new ProgressDialog(this);
//                pubClass.dialog.setTitle("正在提交请稍后...");
//                pubClass.dialog.show();
//                try {
//                    OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm,callback,map);
//                    //
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
                Map<String, String> map = new HashMap<>();
                map.put("task", "addSchToServerWithType");
                map.put("schjson", JSON.toJSONString(bean));
                pubClass.dialog = new ProgressDialog(this);
                pubClass.dialog.setTitle("正在提交请稍后...");
                pubClass.dialog.show();
                try {
                    OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                        @Override
                        public void onSuccess(String result) {
                            //保存本地，跳转执行任务
                            String[] resArry= result.split("\\|");
                            int schid=0;
                            if (resArry[0].equals("200")){
                                AsynData ad =new AsynData(null);
                                ad.asynScheduleData(result);
                                Gson gson =new Gson();
                                Type typeList = new TypeToken<ArrayList<Schedule>>(){}.getType();
                                ArrayList<Schedule> Schedules = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                                for (Schedule sch:Schedules){
                                    schid = sch.getID();
                                }
                                //是否存储在本地
                                try {
                                    Schedule schedule = db.selector(Schedule.class).where("ID","=",schid).findFirst();
                                    if (schedule==null){
                                        BaseActivity.showAnimaDialog(schAddForOE.this,"任务保存失败");
                                    }else{
                                        //判断是否签到
                                        showSignDialog(schedule);
                                    }
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }

                            }

                            if(pubClass.dialog!=null){
                                pubClass.dialog.dismiss();
                            }

                        }
                        @Override
                        public void onFailture() {
                            if(pubClass.dialog!=null) {
                                pubClass.dialog.setTitle("提交失败，请检查网络状况");
                            }
                        }
                    }, map);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                BaseActivity.showAnimaDialog(this, "请检查网络连接");
            }
        }
    }
    //清空数据
    private void clearData(){
        //清空str
        storeStr="";
        typeStr="";
        storeid="";
        typeid="";
        addTaskType.setText("请选择任务类型");
        addStore.setText("请选择餐厅");
    }

    public void YEARMMDD()
    {
        Calendar c = Calendar.getInstance();
        int year=c.get(Calendar.YEAR);
        int month=c.get(Calendar.MONTH)+1;
        int day=c.get(Calendar.DAY_OF_MONTH);
        int hour=c.get(Calendar.HOUR_OF_DAY);
        int minutes=c.get(Calendar.MINUTE);
        sYear=String.valueOf(year);
        sMonth=month+"";
        sDay=day+"";
        sHH=hour+"";
        sMM=minutes+"";
        if(String.valueOf(month).length()==1)
        {
            sMonth="0"+month;
        }
        if(String.valueOf(day).length()==1)
        {
            sDay="0"+day;
        }
        if(String.valueOf(hour).length()==1)
        {
            sHH="0"+hour;
        }
        if(String.valueOf(minutes).length()==1)
        {
            sMM="0"+minutes;
        }
    }


    public void showMyExitDialg(){
        MaterialDialogUtils.showMaterialDialog(this, "是否放弃添加评任务", "确定", "取消", true,false,
                new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                finish();
            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });

    }
/*是否签到*/
public void showSignDialog(final Schedule schedule){

    try {
        SignUpInfo sui = db.selector(SignUpInfo.class).where("shopId", "=", schedule.getShopID())
                .and("empId","=", MainActivity.id)
                .and("outTime","=",null)
                .findFirst();
        if (sui==null){
            MaterialDialogUtils.showMaterialDialog(this, "当前门店没进行签到，是否去该门店签到？"+"\n"+"tip：签到才能执行任务",
                    "确定", "取消", false,true,
                    new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            try {
                                Shop  shop = db.selector(Shop.class).where("ID","=",schedule.getShopID()).findFirst();
                                Intent in=new Intent(schAddForOE.this,SignInActivity.class).putExtra("shopId",schedule.getShopID());
                                in.putExtra("xcol",shop.getxCol());
                                in.putExtra("ycol", shop.getyCol());
                                in.putExtra("shopName", shop.getShopName());
                                startActivity(in);
                                finish();
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            finish();
                        }
                    });
        }else{
            Intent in = new Intent(schAddForOE.this, WrittingEvaluationListActivity.class);
            in.putExtra("rrschid",schedule.getID());
            startActivity(in);
        }

    } catch (DbException e) {
        e.printStackTrace();
    }

}
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            showMyExitDialg();
            return false;
        }else{
            return super.onKeyDown(keyCode, event);
        }
    }
}
